package com.hsyt.pms.controller;

import com.hsyt.pms.security.rsa.RsaKeyPairQueue;
import com.hsyt.pms.controller.base.BaseController;
import com.hsyt.pms.security.rsa.util.RsaKeyPair;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

/**
 * @ClassName: IndexController
 * @Description: 首页控制器跳转
 * @author 王勇琳
 * @date 2017年7月5日 下午1:54:08
 */
@Slf4j
@Controller
public class IndexController extends BaseController {
	
	/** 用户业务错误信息显示的常量变量名 */
	private static final String ERROR_MSG = "errorMsg";
	/** rsa公钥常量变量名 */
	private static final String PUBLIC_KEY = "publicKey";

	@Resource(name="rsaKeyPairQueue")
	private RsaKeyPairQueue rsaKeyPairQueue;
	
	@RequestMapping(value = "/home")
	public String home(Model model, HttpServletRequest request) {
		this.setModelAttr(model, request);
		return "/home";
	}
	
	@RequestMapping(value = "/home/{errorMsg}")
	public String homeError(@PathVariable String errorMsg, Model model, HttpServletRequest request) {
		if(StringUtils.isNotBlank(errorMsg)){
			model.addAttribute(ERROR_MSG, new String(Base64.decodeBase64(errorMsg)));
		}else{
			model.addAttribute(ERROR_MSG, "");
		}
		this.setModelAttr(model, request);
		return "/home";
	}
	
	private void setModelAttr(Model model, HttpServletRequest request){
		RsaKeyPair keyPair;
		try {
			keyPair = rsaKeyPairQueue.takeQueue(request);
			model.addAttribute(PUBLIC_KEY, keyPair.getPublicKey());
		} catch (InterruptedException e) {
			log.error("进入首页时，rsa公私钥队列相关操作异常", e);
		}
	}


	@RequestMapping(value = "/timeout")
	public String timeout(Model model, HttpServletRequest request) {
		return "timeOutPage";
	}
}
